package com.sinry.gateway.config;

import com.sinry.common.log.utils.TraceIdUtil;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * @author linxinlei
 * @project sinry-cloud
 * @description 网关全局配置
 * @date 2022/5/31
 **/
@Configuration
public class GlobalConfig {

    @Bean
    public GlobalFilter globalFilter() {
        return (exchange, chain) -> {
            // mutate()通过使用ServerHttpRequestDecorator包装它并返回变异值或委托回此实例，返回一个构建器以更改此请求的属性。
            ServerHttpRequest request = exchange.getRequest().mutate()
                    .headers(requestHeader -> {
                        requestHeader.add(TraceIdUtil.TRACE_ID, TraceIdUtil.genTraceId());
                        requestHeader.add(TraceIdUtil.PARENT_ID, TraceIdUtil.genSpanId());
                    })
                    .build();
            // 重写入request
            return chain.filter(exchange.mutate().request(request).build());
        };
    }
}
